package org.xuk.spring.ws.consumer;

import com.google.gson.Gson;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.xuk.spring.ws.constants.WsConstants;
import org.xuk.spring.ws.model.BoardCastMessage;
import org.xuk.spring.ws.model.SingleMessage;
import org.xuk.spring.ws.service.ReceivedMessageHandler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class MessageReceiveConsumer {

    private final Gson gson;
    private final ReceivedMessageHandler receivedMessageHandler;

    public MessageReceiveConsumer(Gson gson, ReceivedMessageHandler receivedMessageHandler) {
        this.gson = gson;
        this.receivedMessageHandler = receivedMessageHandler;
    }

    @RabbitListener(bindings = @QueueBinding(value = @Queue(),
            exchange = @Exchange(value = WsConstants.SINGLE_EXCHANGE, type = ExchangeTypes.FANOUT)))
    public void handleSingleMessage(Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        String body = new String(message.getBody(), StandardCharsets.UTF_8);
        SingleMessage singleMessage = gson.fromJson(body, SingleMessage.class);
        receivedMessageHandler.handleSingleMessage(singleMessage);
        channel.basicAck(tag, false);
    }


    @RabbitListener(bindings = @QueueBinding(value = @Queue(),
            exchange = @Exchange(value = WsConstants.BOARD_CAST_EXCHANGE, type = ExchangeTypes.FANOUT)))
    public void handleBoardCastMessage(Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        String body = new String(message.getBody(), StandardCharsets.UTF_8);
        BoardCastMessage boardCastMessage = gson.fromJson(body, BoardCastMessage.class);
        receivedMessageHandler.handleBoardCastMessage(boardCastMessage);
        channel.basicAck(tag, false);
    }
}
